package com.sl.mes.app.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

@SuppressWarnings("unchecked")
public class MessageToOaTools {

	/**
	 * OA消息发送后，后继单起线程处理
	 */
	public static void exeSendMessageToOaTask(String[] pk_messages) {

		final Map<String, String> paramsMap = getSendToOaMessage(pk_messages);

		Runnable msgSendToOaRun = new Runnable() {
			public void run() {
				try {
					MessageToOaTools.exeApplyMobileRequest(paramsMap);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		// 先启用线程
		new Thread(msgSendToOaRun).start();

	}

	/**
	 * 根据消息pk获取发送消息MAP
	 *
	 * @param pk_messages
	 * @return
	 */
	public static Map<String, String> getSendToOaMessage(String[] pk_messages) {
		HashMap<String, String> rtMap = new HashMap<String, String>();
		String ncMsgStr = "";
		try {
			Map<String, Object> ncMsgMap =new HashMap<>() ;//待修订
			ncMsgStr = JsonHandler.map2json(ncMsgMap);
		} catch (Exception e) {

		}
		rtMap.put("method", "send");
		rtMap.put("ncmsg", ncMsgStr);

		return rtMap;
	}


	/**
	 * 调用移动服务的信息发送请求
	 * 
	 * @throws Exception
	 */
	public static String exeApplyMobileRequest(Map<String, String> paramsMap) throws Exception {

		// 第一步：API服务地址
		String strDomain = "/donorapprove/sendmsghandler.json";

		HttpPost httpPost = new HttpPost(strDomain);

		// 第二步：转换POST表单Map并放入请求体
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		Iterator<Entry<String, String>> iterator = paramsMap.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<String, String> elem = iterator.next();
			list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
		}
		if (list.size() > 0) {
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
			httpPost.setEntity(entity);
		}

		// 第三步：发送http post请求，并得到相应结果
		String result = "";
		HttpResponse response = HttpUtil.getHttpClient().execute(httpPost);

		if (response != null) {
			HttpEntity resEntity = response.getEntity();
			if (resEntity != null) {
				result = EntityUtils.toString(resEntity, "UTF-8");
				System.out.println(result);
			}
		}
		return result;
	}


}
